<template>
  <div class="user-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="is_admin" label="管理员" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_admin === 1 ? 'success' : 'info'">
              {{ row.is_admin === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
        autocomplete="off"
      >
        <el-form-item label="用户名" prop="username" v-if="!isEdit">
          <el-input v-model="userForm.username" placeholder="请输入用户名" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item label="修改密码" prop="password" v-if="isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="留空则不修改密码"
            show-password
            autocomplete="new-password"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 4px">
            留空则不修改密码
          </div>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-select v-model="userForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限" prop="permission_ids">
          <el-select
            v-model="userForm.permission_ids"
            placeholder="请选择权限"
            multiple
            filterable
            style="width: 100%"
            :loading="permissionLoading"
          >
            <el-option
              v-for="permission in permissionList"
              :key="permission.id"
              :label="`${permission.name} (${permission.code})`"
              :value="permission.id"
            >
              <span>{{ permission.name }}</span>
              <span style="color: #8492a6; font-size: 13px; margin-left: 8px">
                {{ permission.code }}
              </span>
            </el-option>
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 4px">
            可多选，留空则不设置权限
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  getUserList,
  createUser,
  updateUser,
  deleteUser,
  getUserDetail,
  type UserData,
  type CreateUserParams,
  type UpdateUserParams
} from '@/api/users'
import { getAllPermissionList, type Permission } from '@/api/permissions'
import { valids } from '@/utils'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const userFormRef = ref<FormInstance>()
const permissionLoading = ref(false)
const permissionList = ref<Permission[]>([])

const searchForm = reactive({
  username: '',
  status: undefined as number | undefined
})

const tableData = ref<UserData[]>([])

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const userForm = reactive<CreateUserParams & { id?: string; status?: number; permission_ids?: string[] }>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  status: 1,
  permission_ids: []
})

const userFormRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (!isEdit.value && !value) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
        } else if (!valids.isEmail(value)) {
          callback(new Error('请输入正确的邮箱格式'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
        } else if (!valids.isMobile(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const dialogTitle = computed(() => (isEdit.value ? '编辑用户' : '新增用户'))

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      pageSize: pagination.size
    }
    if (searchForm.username) {
      params.username = searchForm.username
    }
    if (searchForm.status !== undefined) {
      params.status = searchForm.status
    }

    const res = await getUserList(params)
    tableData.value = res.data.list
    pagination.total = res.data.total
    pagination.page = res.data.page
    pagination.size = res.data.pageSize
  } catch (error: any) {
    ElMessage.error(error.message || '加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadUserList()
}

// 重置
const handleReset = () => {
  searchForm.username = ''
  searchForm.status = undefined
  pagination.page = 1
  loadUserList()
}

// 加载权限列表
const loadPermissionList = async () => {
  if (permissionList.value.length > 0) {
    return // 已加载过，不再重复加载
  }
  permissionLoading.value = true
  try {
    const res = await getAllPermissionList()
    permissionList.value = res.data.list
  } catch (error: any) {
    ElMessage.error(error.message || '加载权限列表失败')
  } finally {
    permissionLoading.value = false
  }
}

// 新增用户
const handleAdd = async () => {
  isEdit.value = false
  dialogVisible.value = true
  resetUserForm()
  await loadPermissionList()
}

// 编辑用户
const handleEdit = async (row: UserData) => {
  isEdit.value = true
  dialogVisible.value = true
  loading.value = true
  try {
    await loadPermissionList()
    const res = await getUserDetail({ id: row.id })
    const user = res.data
    userForm.id = user.id
    userForm.nickname = user.nickname
    userForm.email = user.email
    userForm.phone = user.phone
    userForm.status = user.status
    // 设置已选权限
    userForm.permission_ids = user.permissions?.map(p => p.id) || []
  } catch (error: any) {
    ElMessage.error(error.message || '获取用户详情失败')
    dialogVisible.value = false
  } finally {
    loading.value = false
  }
}

// 删除用户
const handleDelete = (row: UserData) => {
  ElMessageBox.confirm(`确定要删除用户 "${row.username}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteUser({ id: row.id })
        ElMessage.success('删除成功')
        loadUserList()
      } catch (error: any) {
        ElMessage.error(error.message || '删除失败')
      }
    })
    .catch(() => {})
}

// 重置表单
const resetUserForm = () => {
  userForm.username = ''
  userForm.password = ''
  userForm.nickname = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.status = 1
  userForm.id = undefined
  userForm.permission_ids = []
  userFormRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          // 更新用户
          const updateParams: UpdateUserParams = {
            id: userForm.id!,
            nickname: userForm.nickname,
            email: userForm.email,
            phone: userForm.phone,
            status: userForm.status,
            permission_ids: userForm.permission_ids && userForm.permission_ids.length > 0 ? userForm.permission_ids : undefined
          }
          // 如果密码不为空，则包含在更新参数中
          if (userForm.password && userForm.password.trim()) {
            updateParams.password = userForm.password
          }
          await updateUser(updateParams)
          ElMessage.success('更新成功')
        } else {
          // 创建用户
          const createParams: CreateUserParams = {
            username: userForm.username,
            password: userForm.password,
            nickname: userForm.nickname,
            email: userForm.email,
            phone: userForm.phone,
            permission_ids: userForm.permission_ids && userForm.permission_ids.length > 0 ? userForm.permission_ids : undefined
          }
          await createUser(createParams)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        loadUserList()
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新失败' : '创建失败'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetUserForm()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadUserList()
}

// 页码改变
const handlePageChange = (page: number) => {
  pagination.page = page
  loadUserList()
}

onMounted(() => {
  loadUserList()
})
</script>

<style scoped lang="scss">
.user-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

